#include "stdafx.h"
#include "doc.h"

XmlElement::XmlElement(IXMLDOMElement *pElement,bool stealRef)
{
	this->pElement = pElement;
	if(!stealRef)
		pElement->AddRef();
}

XmlElement::XmlElement(const XmlElement &src)
{
	pElement = (IXMLDOMElement*)src.pElement;
	pElement->AddRef();
}

XmlElement::~XmlElement()
{
	pElement->Release();
}

XmlElement XmlElement::AddNewElement(const std::string &name)
{
	IXMLDOMDocument *pDoc;
	HRESULT hres = pElement->get_ownerDocument(&pDoc);
	assert(hres == S_OK);

	IXMLDOMElement *pNewElement;

	BSTR nameBStr = _com_util::ConvertStringToBSTR(name.c_str());
	hres = pDoc->createElement(nameBStr,&pNewElement);
	assert(hres == S_OK);
	SysFreeString(nameBStr);
	
	IXMLDOMNode *pNode;
	pElement->appendChild(pNewElement,&pNode);

	pDoc->Release();
	pNewElement->Release();

	hres = pNode->QueryInterface(IID_IXMLDOMElement,(void**)&pNewElement);
	assert(hres == S_OK);
	pNode->Release();

	return XmlElement(pNewElement,true);	
}

void XmlElement::AddNewAttribute(const std::string &name,const std::string &value)
{
	BSTR nameBSTR = _com_util::ConvertStringToBSTR(name.c_str());
	BSTR valueBSTR = _com_util::ConvertStringToBSTR(value.c_str());
	HRESULT hres = pElement->setAttribute(nameBSTR,_variant_t(valueBSTR));
	assert(hres == S_OK);

	SysFreeString(nameBSTR);
	SysFreeString(valueBSTR);
}